//
//  LHCameraViewController.m
//  LHCemera
//
//  Created by LH on 16/9/2.
//  Copyright © 2016年 LH. All rights reserved.
//
/*
                    _ooOoo_
                   o8888888o
                   88" . "88
                   (| -_- |)
                   O\  =  /O
                ____/`---'\____
              .'  \\|     |//  `.
            /  \\|||  :  |||//  \
            /  _||||| -:- |||||-  \
            |   | \\\  -  /// |   |
            | \_|  ''\---/''  |   |
            \  .-\__  `-`  ___/-. /
            ___`. .'  /--.--\  `. . __
        ."" '<  `.___\_<|>_/___.'  >'"".
    | | :  `- \`.;`\ _ /`;.`/ - ` : | |
    \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
               `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                佛祖保佑       永无BUG
 */
#import "LHCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LHSaveViewController.h"
@interface LHCameraViewController ()<UIGestureRecognizerDelegate>
//定义枚举类型
typedef enum {
    ENUM_ViewController_ActionTypeStart=0,//开始
    ENUM_ViewController_ActionTypeStop,//停止
    ENUM_ViewController_ActionTypePause//暂停
} ActionType;

//-------in parameters---------------
@property (nonatomic,assign) NSInteger InActionType; //操作类型
/**
 *  相机显示区域
 */
@property (weak, nonatomic) IBOutlet UIView *cameraView;
/**
 *  水印区域
 */
@property (weak, nonatomic) IBOutlet UIView *logoView;
/**
 *  工具栏
 */
@property (weak, nonatomic) IBOutlet UIView *toolView;
/**
 *  设备之间的数据传递  第一个创建
 */
@property (nonatomic, strong)AVCaptureSession           * session;
/**
 *  输入流->笔者认为是相机
 */
@property (nonatomic, strong)AVCaptureDeviceInput       * videoInput;
/**
 *  照相机
 */
@property (nonatomic, strong)AVCaptureStillImageOutput  * stillImageOutput;
/**
 *  显示层 (相框) 要第二个创建
 */
@property (nonatomic, strong)AVCaptureVideoPreviewLayer * previewLayer;
/**
 *  水印照片
 */
@property (weak, nonatomic) IBOutlet UIImageView *logoImageVIew;
/**
 *  记录开始的缩放比例
 */
@property(nonatomic,assign)CGFloat beginGestureScale;
/**
 *  最后的缩放比例
 */
@property(nonatomic,assign)CGFloat effectiveScale;
/**
 *  对焦图像
 */
@property (nonatomic)UIView *focusView;
@end

@implementation LHCameraViewController
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    if (self.session) {
        
        [self.session startRunning];
    }
}


- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:YES];
    
    if (self.session) {
        
        [self.session stopRunning];
    }
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self initAVCaptureSession];
    }
    return  self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.effectiveScale = self.beginGestureScale = 1.0f;
    self.view.clipsToBounds = NO;
    self.view.backgroundColor = [UIColor blackColor];
    [self setUpGesture];//焦距手势 对焦手势
    [self initFocusView];
    [self setUpCameraLayer];
}
/**
 *   初始化对焦图像
 *   @author FlashMan
 */
-(void)initFocusView{
    _focusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    _focusView.layer.borderWidth = 1.0;
    _focusView.layer.borderColor =[UIColor greenColor].CGColor;
    _focusView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_focusView];
    _focusView.hidden = YES;
}
/**
 *  初始化
 */
-(void)initAVCaptureSession{
    self.session = [[AVCaptureSession alloc] init];
    //     拿到的图像的大小可以自行设定
    //    AVCaptureSessionPreset320x240
    //    AVCaptureSessionPreset352x288
    //    AVCaptureSessionPreset640x480
    //    AVCaptureSessionPreset960x540
    //    AVCaptureSessionPreset1280x720
    //    AVCaptureSessionPreset1920x1080
    //    AVCaptureSessionPreset3840x2160
    //    self.session.sessionPreset = AVCaptureSessionPreset640x480;
    self.session.sessionPreset = AVCaptureSessionPresetPhoto;
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:nil];
    
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    //以JPEG的图片格式输出图片
    [self.stillImageOutput setOutputSettings:outputSettings];
    //输入输出设备结合
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
}
//后置摄像头
- (AVCaptureDevice *)backCamera {
    
    AVCaptureDevice *captureDevice = [self cameraWithPosition:AVCaptureDevicePositionBack];
    //更改这个设置的时候必须先锁定设备，修改完后再解锁，否则崩溃
    [captureDevice lockForConfiguration:nil];
    //设置闪光灯为自动
    [captureDevice setFlashMode:AVCaptureFlashModeAuto];
    [captureDevice unlockForConfiguration];
    
    return captureDevice;
}
//前置摄像头
- (AVCaptureDevice *)frontCamera {
    AVCaptureDevice *captureDevice = [self cameraWithPosition:AVCaptureDevicePositionFront];
    return captureDevice;
}
/**
 *  获取前后摄像头对象的方法
 */
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == position) {
            return device;
        }
    }
    return nil;
}
/**
 *  设置相机layer
 */
- (void) setUpCameraLayer
{
    
    if (self.previewLayer == nil) {
        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        
        UIView * view = self.cameraView;
        CALayer * viewLayer = [view layer];
        [viewLayer setMasksToBounds:YES];
        
        CGRect bounds = [view bounds];
        bounds.size.width = [UIScreen mainScreen].bounds.size.width;
        bounds.size.height = [UIScreen mainScreen].bounds.size.height -160;
        [self.previewLayer setFrame:bounds];
        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        
        [viewLayer insertSublayer:self.previewLayer below:[[viewLayer sublayers] objectAtIndex:0]];
    }
}
- (IBAction)takePictureClick:(id)sender {
    [self shutterCamera];
}
#pragma mark -- 拍照

- (void) shutterCamera
{
    AVCaptureConnection * videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    
    //焦距调节
    [videoConnection setVideoScaleAndCropFactor:self.effectiveScale];
    
    if (!videoConnection) {
        NSLog(@"拍照失败");
        return;
    }
    
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        
        //照片
        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage * image = [UIImage imageWithData:imageData];
        NSLog(@"成功");
        LHSaveViewController *saVC = [[LHSaveViewController alloc] initWithNibName:@"LHSaveViewController" bundle:nil];
        UIImage *logo = self.logoImageVIew.image;
        [self presentViewController:saVC animated:YES completion:^{
            [saVC setPhotoImage:image logoImage:logo];
        }];
    }];
}
/**
 *   修改闪光灯模式
 *   @author FlashMan
 */
- (IBAction)flashButClick:(UIButton *)sender {
    NSLog(@"flashButtonClick");
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //修改前必须先锁定
    [device lockForConfiguration:nil];
    //必须判定是否有闪光灯，否则如果没有闪光灯会崩溃
    if ([device hasFlash]) {
        if (device.flashMode == AVCaptureFlashModeOff) {
            device.flashMode = AVCaptureFlashModeOn;
            //[sender setTitle:@"flashOn"];
            [sender setTitle:@"flashOn" forState:UIControlStateNormal];
             NSLog(@"flashOn");
        } else if (device.flashMode == AVCaptureFlashModeOn) {
            device.flashMode = AVCaptureFlashModeAuto;
           // [sender setTitle:@"flashAuto"];
            [sender setTitle:@"flashAuto" forState:UIControlStateNormal];
             NSLog(@"flashAuto");
        } else if (device.flashMode == AVCaptureFlashModeAuto) {
            device.flashMode = AVCaptureFlashModeOff;
           // [sender setTitle:@"flashOff"];
            [sender setTitle:@"flashOff" forState:UIControlStateNormal];
             NSLog(@"flashOff");
        }
        
    } else {
        
        NSLog(@"设备不支持闪光灯");
    }
    [device unlockForConfiguration];
}
/**
 *  前后摄像头切换
 */
- (IBAction)changeCameraClick:(UIButton *)sender {
    [self toggleCamera];
}
/**
 *  前后摄像头切换
 */
- (void)toggleCamera {
    
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        AVCaptureDeviceInput *newVideoInput;
        AVCaptureDevicePosition position = [[_videoInput device] position];
        
        if (position == AVCaptureDevicePositionBack)
            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:&error];
        else if (position == AVCaptureDevicePositionFront)
            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:&error];
        
        else
            return;
        
        if (newVideoInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:self.videoInput];
            if ([self.session canAddInput:newVideoInput]) {
                [self.session addInput:newVideoInput];
                [self setVideoInput:newVideoInput];
            } else {
                [self.session addInput:self.videoInput];
            }
            [self.session commitConfiguration];
        } else if (error) {
            NSLog(@"打开失败 %@", error);
        }
    }
}
/**
 *   logo选择
 *   @author FlashMan
 */
- (IBAction)choseLogo:(UIButton*)sender {
    switch (sender.tag) {
        case 0:
        {
            //不选
            self.logoImageVIew.image = nil;
        }
            break;
        case 1:
        {
            self.logoImageVIew.image = [UIImage imageNamed:@"1111"];
        }
            break;
        case 2:
        {
            self.logoImageVIew.image = [UIImage imageNamed:@"2222"];
        }
            break;
        case 3:
        {
            self.logoImageVIew.image = [UIImage imageNamed:@"3333"];
        }
          break;
        case 4:
        {
            self.logoImageVIew.image = [UIImage imageNamed:@"4444"];
        }
            break;
        default:
            break;
    }
}

/**
 *   焦距手势 对焦手势
 *   @author FlashMan
 */
#pragma 创建手势
- (void)setUpGesture{
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
    pinch.delegate = self;
    [self.cameraView addGestureRecognizer:pinch];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusGesture:)];
    [self.cameraView addGestureRecognizer:tapGesture];
}
//对焦手势
- (void)focusGesture:(UITapGestureRecognizer*)gesture{
    CGPoint point = [gesture locationInView:gesture.view];
    [self focusAtPoint:point];
}
#pragma mark gestureRecognizer delegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
        self.beginGestureScale = self.effectiveScale;
    }
    return YES;
}
- (void)focusAtPoint:(CGPoint)point{
    CGSize size = self.view.bounds.size;
    CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
    NSError *error;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device lockForConfiguration:&error]) {
        
        if ([device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [device setFocusPointOfInterest:focusPoint];
            [device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        
        if ([device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
            [device setExposurePointOfInterest:focusPoint];
            [device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        
        [device unlockForConfiguration];
        _focusView.center = point;
        _focusView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                _focusView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                _focusView.hidden = YES;
            }];
        }];
    }
    
}
//缩放手势 用于调整焦距
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer{
    
    BOOL allTouchesAreOnThePreviewLayer = YES;
    NSUInteger numTouches = [recognizer numberOfTouches], i;
    for ( i = 0; i < numTouches; ++i ) {
        CGPoint location = [recognizer locationOfTouch:i inView:self.cameraView];
        CGPoint convertedLocation = [self.previewLayer convertPoint:location fromLayer:self.previewLayer.superlayer];
        if ( ! [self.previewLayer containsPoint:convertedLocation] ) {
            allTouchesAreOnThePreviewLayer = NO;
            break;
        }
    }
    
    if ( allTouchesAreOnThePreviewLayer ) {
        
        
        self.effectiveScale = self.beginGestureScale * recognizer.scale;
        if (self.effectiveScale < 1.0){
            self.effectiveScale = 1.0;
        }
        
        NSLog(@"%f-------------->%f------------recognizerScale%f",self.effectiveScale,self.beginGestureScale,recognizer.scale);
        
        CGFloat maxScaleAndCropFactor = [[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor];
        
        NSLog(@"%f",maxScaleAndCropFactor);
        if (self.effectiveScale > maxScaleAndCropFactor)
            self.effectiveScale = maxScaleAndCropFactor;
        
        [CATransaction begin];
        [CATransaction setAnimationDuration:.025];
        [self.previewLayer setAffineTransform:CGAffineTransformMakeScale(self.effectiveScale, self.effectiveScale)];
        [CATransaction commit];
        
    }
    
}
/**
 *   退出拍照
 *   @author FlashMan
 */
- (IBAction)cancelClick:(UIButton *)sender {
    if (self.navigationController.viewControllers.count >1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}



@end
